<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="租户名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="所在地区" prop="regionCode">-->
<!--        <el-input-->
<!--          v-model="queryParams.regionCode"-->
<!--          placeholder="请输入所在地区 "-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="租户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="租户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.yt_tenant_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="租户类型" prop="tenantType">
        <el-select
          v-model="queryParams.tenantType"
          placeholder="租户类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.yt_tenant_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="创建者" prop="createUser">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.createUser"-->
      <!--          placeholder="请输入创建者"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="更新者" prop="updateUser">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.updateUser"-->
      <!--          placeholder="请输入更新者"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['b:tenant:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['b:tenant:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['b:tenant:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['b:tenant:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="租户id" align="center" prop="id"/>
      <el-table-column label="租户名称" align="center" prop="tenantName"/>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="租户类型" align="center" prop="tenantType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yt_tenant_type" :value="scope.row.tenantType"/>
        </template>
      </el-table-column>
      <el-table-column label="成员规模" align="center" prop="tenantSize"/>
      <el-table-column label="企业类型" align="center" prop="industryType"/>
      <el-table-column label="用户数量" align="center" prop="userAmount">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handlerQueryByTenantId(scope.row)"
            v-hasPermi="['b:tenant:edit']"
          >{{ scope.row.userAmount }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="所在区域" align="center" prop="regionCode"/>
      <el-table-column label="邀请码" align="center" prop="inviteCode"/>
      <el-table-column label="邀请码过期时间" align="center" prop="inviteCodeExpireTime"/>
      <el-table-column label="租户状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yt_tenant_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="开通时间" align="center" prop="createTime">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['b:tenant:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['b:tenant:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租户名称:" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称"/>
        </el-form-item>
        <el-form-item label="描述:" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="类型:" prop="tenantType">
          <el-radio-group v-model="form.tenantType">
            <el-radio v-for="d in dict.type.yt_tenant_type" :value="d.value" :label="d.value" :key="d.value">
              {{ d.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="*状态:" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="f in dict.type.yt_tenant_status" :value="f.value" :label="f.value" :key="f.value">
              {{ f.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成员规模:" prop="tenantSize">
          <el-input v-model="form.tenantSize" placeholder="请输入租户规模"/>
        </el-form-item>
        <el-form-item label="所在地区:" prop="regionCode">
          <el-input v-model="form.regionCode" placeholder="请输入所在地区"/>
        </el-form-item>
        <el-form-item label="企业类型:" prop="industryType">
          <el-input v-model="form.industryType" placeholder="请输入所在地区"/>
        </el-form-item>
<!--        this.title = "新增租户";-->

        <el-form-item label="分配系统管理员:" prop="inviteCode" label-width="120px" v-if="title !== '新增租户'">
          <el-button type="primary" @click="updateInviteCode" icon="el-icon-search">
            刷新邀请码
          </el-button>
          <el-button type="success"  icon="el-icon-copy-document"  v-if="inviteCode"   @click="copyInviteCode">
            {{ inviteCode }}
          </el-button>
        </el-form-item>

        <el-form-item label="功能配置">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <!--        <el-form-item label="租户状态" prop="status">-->

        <!--        </el-form-item>-->
        <!--        <el-form-item label="创建者" prop="createUser">-->
        <!--          <el-input v-model="form.createUser" placeholder="请输入创建者" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="更新者" prop="updateUser">-->
        <!--          <el-input v-model="form.updateUser" placeholder="请输入更新者" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改租户管理对话框 -->
    <el-dialog :title="findUserTitle" :visible.sync="openUser" width="100%" append-to-body>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column label="用户id" align="center" prop="id"/>
        <el-table-column label="用户名" align="center" prop="username"/>
        <el-table-column label="手机号码" align="center" prop="phoneNumber"/>
        <el-table-column label="用户邮箱" align="center" prop="email"/>
        <el-table-column label="是否系统管理员" align="center" prop="isAdmin">
          <template slot-scope="scope">
            {{ scope.row.isAdmin ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.normal_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.isAdmin"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="updateUserAdmin(scope.row)"
            >设置管理员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="subTotal>0"
        :total="subTotal"
        :page.sync="subQueryParams.pageNum"
        :limit.sync="subQueryParams.pageSize"
        @pagination="getUserListByTenantId"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addTenant, delTenant, getTenant, getUserByTenant, listTenant, updateTenant,setUserIsAdmin} from "@/api/tenant/tenant";
import {genInviteCode} from "@/api/tenant/InviteCode";
import {treeselect as menuTreeselect, tenantMenuTreeselect} from "@/api/resource";
import {roleMenuTreeselect} from "@/api/system/menu";

export default {
  name: "Tenant",
  dicts: ['yt_tenant_status', 'yt_tenant_type','normal_status'],
  data() {
    return {

      defaultProps: {
        children: "children",
        label: "label"
      },
      menuCheckStrictly: true,
      // 菜单列表
      menuOptions: [],
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      inviteCode: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      subTotal: 0,
      // 租户管理表格数据
      tenantList: [],

      userList: [],
      // 弹出层标题
      title: "",
      findUserTitle: "查看关联用户",
      // 是否显示弹出层
      open: false,
      openUser: false,
      curTenantId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        tenantType: null,
        industryType: null,
        tenantSize: null,
        regionCode: null,
        status: null,
        createUser: null,
        updateUser: null
      },
      subQueryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        isAdmin: false,
        createUser: null,
        updateUser: null,
        tenantId: null,
      },
      // 表单参数
      form: {},

      formUser: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {

    updateUserAdmin(row) {
      console.log(JSON.stringify(row))
      let userId = row.id;
      let tenantId = this.curTenantId;
      setUserIsAdmin(userId, tenantId)
      this.$message.success('更新成功，请重新进入！');
      this.openUser = false;
    },

    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },

    /** 根据角色ID查询菜单树结构 */
    getTenantMenuTreeselect(roleId) {
      return tenantMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    copyInviteCode() {
      const result = navigator.clipboard.writeText(this.inviteCode);
      if (result) {
        result.then(() => {
          // 复制成功的操作
          this.$message.success('邀请码复制成功！');
        }, (error) => {
          // 复制失败的处理
          this.$message.error('复制失败，请重试！');
          console.error('Failed to copy: ', error);
        });
      } else {
        // Clipboard API 不支持的处理
        this.$message.error('您的浏览器不支持自动复制。');
      }
    },
    updateInviteCode() {
      let that = this;
      this.$modal.confirm('是否确认生成邀请码？').then(function () {
        console.log("生成邀请码")
        console.log(that.form)
        genInviteCode({"tenantId": that.form.id}).then(response => {
          console.log(`that.inviteCode is ${that.inviteCode}`)
          that.inviteCode = response.msg;
          that.$modal.msgSuccess("生成邀请码成功");
        });
      });
    },
    /** 查询忆图用户列表 */
    getUserListByTenantId() {
      this.loading = true;
      getUserByTenant(this.subQueryParams).then(response => {
        this.userList = response.rows;
        this.subTotal = response.total;
        this.loading = false;
      });
    },

    /** 查询租户管理列表 */
    getList() {
      this.loading = true;
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openUser = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          inviteCode: undefined,
          inviteCodeExpireTime: undefined,
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.form = {
        id: null,
        inviteCodeExpireTime: undefined,
        tenantName: null,
        tenantType: null,
        tenantSize: null,
        regionCode: null,
        description: null,
        status: null,
        inviteCode: null,
        userAmount: null,
        updateTime: null,
        createTime: null,
        createUser: null,
        updateUser: null
      };
      this.resetForm("form");
      this.formUser = {
        id: null,
        username: null,
        email: null,
        password: null,
        status: null,
        isAdmin: null,
        createTime: null,
        updateTime: null,
        phoneNumber: null,
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "新增租户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.inviteCode = "";
      this.reset();
      const id = row.id || this.ids

      getTenant(id).then(response => {

        const tenantMenu = this.getTenantMenuTreeselect(id);
        this.$nextTick(() => {
          tenantMenu.then(res => {
            console.log(`res is ${res}`)
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(v, true ,false);
              })
            })
          });
        });
        this.form = response.data;
        this.open = true;
        this.title = "修改租户信息";
      });
    },
    // /** 查询租户关联的用户列表 */
    handlerQueryByTenantId(row) {
      this.reset();
      console.log(row.id)
      // this.formUser = response.data;
      this.subQueryParams.tenantId = row.id || this.ids;
      getUserByTenant(this.subQueryParams).then(response => {
        this.curTenantId = row.id;
        this.openUser = true;
        this.findUserTitle = "查看关联用户";
        this.userList = response.rows;
        this.subTotal = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {


          // if (this.form.roleId != undefined) {
          //   this.form.menuIds = this.getMenuAllCheckedKeys();
          //   updateRole(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   this.form.menuIds = this.getMenuAllCheckedKeys();
          //   addRole(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }


          if (this.form.id != null) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateTenant(this.form).then(response => {
              console.log(`this form is ${JSON.stringify(this.form)}`);
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(`this form is ${JSON.stringify(this.form)}`)
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addTenant(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除租户管理编号为"' + ids + '"的数据项？').then(function () {
        return delTenant(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('b/tenant/export', {
        ...this.queryParams
      }, `tenant_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
